import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'UserLocationModelPage.dart';

typedef IndexCallback = void Function(LocationModel model);

class UserLocationPage extends StatefulWidget {
  final bool isSend;
  final String pageType;
  final RefreshController refreshController;
  final IndexCallback chooseV;

  UserLocationPage(this.isSend, this.pageType,
      {Key key, this.refreshController, this.chooseV})
      : super(key: key);

  @override
  _UserLocationPageState createState() => _UserLocationPageState();
}

class _UserLocationPageState extends State<UserLocationPage> {
  // RefreshController _refreshController =
  //     RefreshController(initialRefresh: false);
  int page = 1;
  List<LocationModel> cellArr = [];

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    getCellNews();
    widget.refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    page = page + 1;
    // getCellNews();
    if (mounted) setState(() {});
    widget.refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    print("历史地址界面");
    _onRefresh();
  }

  void getCellNews() {
    DioUtils.postHttp(
      context,
      widget.isSend ? "goodsuser/send_address" : "goodsuser/recive_address",
      parameters: {
        "token": getData("token"),
        "type": widget.pageType,
        "page": page.toString(),
      },
      onSuccess: (t) {
        print("历史地址数据$t");
        LocationListModel model = LocationListModel.fromJson(t);
        if (model.code == 1) {
          if (mounted) {
            setState(() {
              List<LocationModel> arr = model.data;
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        } else {}
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Text textLabel01(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(30),
      ),
    );
  }

  Text textLabel02(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF666666),
        fontSize: setFontSize(24),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: widget.refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: cellArr == null || cellArr.length == 0
            ? Container()
            : ListView.builder(
                itemCount: cellArr.length,
                itemBuilder: _listItemBuilder,
              ),
      ),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return Container(
      color: Color(0xFFEDEDED),
      padding: EdgeInsets.only(top: setHeight(1)),
      child: InkWell(
        onTap: () {
          LocationModel model = cellArr[index];
          widget.chooseV(model);
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(
            setWidth(30),
            setHeight(40),
            setWidth(30),
            setHeight(40),
          ),
          color: Colors.white,
          child: Row(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        LimitedBox(
                          maxWidth: (screenWidth * 3) / 4,
                          child: Text(
                            cellArr[index].realname + cellArr[index].mobile,
                            style: TextStyle(
                              color: Color(0xFF333333),
                              fontSize: setFontSize(30),
                            ),
                          ),
                        ),
                        SizedBox(width: 8),
                        cellArr[index].isDefault != 1
                            ? Container()
                            : Image.asset(
                                widget.isSend
                                    ? "images/LocationTyepImage01.png"
                                    : "images/LocationTyepImage02.png",
                                width: setWidth(120),
                              ),
                      ],
                    ),
                    textLabel02(
                      cellArr[index].address + cellArr[index].buildingNumber,
                    ),
                  ],
                ),
              ),
              InkWell(
                child: Image.asset(
                  "images/MainMoreImage.png",
                  height: setHeight(60),
                ),
                onTap: () {
                  print("object");
                  showView(index);
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  void showView(int index) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      enableDrag: false,
      //设置不能拖拽关闭
      isDismissible: true,
      //设置不能点击消失
      isScrollControlled: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, setBottomSheet) {
            return Container(
              height: setHeight(400),
              // padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Color(0xFFF2F2F2),
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(15),
                    topRight: Radius.circular(15)),
              ),
              // color: Colors.white,
              child: Column(
                children: <Widget>[
                  InkWell(
                    child: showBtnView(1),
                    onTap: () {
                      setBottomSheet(() {
                        if (cellArr[index].isDefault == 1) {
                          showToast(widget.isSend ? "已是默认发货" : "已是默认收货");
                          return;
                        }
                        showBtn(1, index);
                      });
                    },
                  ),
                  Container(
                    color: Color(0xFFD4D4D4),
                    height: 1,
                    // width: screenWidth,
                  ),
                  InkWell(
                    child: showBtnView(2),
                    onTap: () {
                      setBottomSheet(() {
                        print("object");
                        showBtn(2, index);
                      });
                    },
                  ),
                  Container(
                    color: Color(0xFFD4D4D4),
                    height: 10,
                    // width: screenWidth,
                  ),
                  InkWell(
                    child: showBtnView(3),
                    onTap: () {
                      setBottomSheet(() {
                        print("object");
                        showBtn(3, index);
                      });
                    },
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget showBtnView(int index) {
    return Container(
      // color: Colors.red,
      alignment: Alignment.center,
      height: setHeight(120),
      child: Text(
        showbtnString(index),
        style: TextStyle(
          color: Color(0xFF222222),
          fontSize: setFontSize(32),
        ),
      ),
    );
  }

  void showBtn(int type, int index) {
    if (type == 3) {
      Navigator.pop(context);
    } else {
      DioUtils.postHttp(
        context,
        widget.isSend
            ? "goodsuser/config_send_address"
            : "goodsuser/config_recive_address",
        parameters: {
          "token": getData("token"),
          "type": type.toString(),
          "id": cellArr[index].id.toString(),
        },
        onSuccess: (t) {
          MainModel model = MainModel.fromJson(t);
          if (model.code == 1) {
            Navigator.pop(context);
            if (type == 2) {
              _onRefresh();
            } else {
              LocationModel model = cellArr[index];
              widget.chooseV(model);
            }
          }
        },
        onError: (error) {
          print(error);
        },
      );
    }
  }

  String showbtnString(int index) {
    if (index == 1) {
      // return widget.isSend ? "默认发货" : "默认收货";
      return "设置默认";
    } else if (index == 2) {
      return "删除";
    } else {
      return "取消";
    }
  }
}
